﻿using System;
using System.Collections.Generic;
using PharmacyPharnet.Core;
using System.Data.Objects.DataClasses;
using Pharmacy.Data;
using Pharmacy.Data.Repositories;
using Pharmacy.Ultilities;
using Pharmacy.Ultilities.Resources;
using System.Drawing;
using Pharmacy.Data.Entity;
using Pharmacy.Business;
using System.Windows.Forms;
using Pharmacy.ExceptionHandling;
using DevExpress.XtraGrid;
using DevExpress.XtraEditors.Repository;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraGrid.Export;
using DevExpress.XtraExport;
using DevExpress.XtraPrinting;
using Pharmacy.Ultilities.BaseEventArgs;
using DevExpress.XtraGrid.Views.Grid.ViewInfo;
using System.Data;
using PharmacyPharnet.MasterData;

namespace PharmacyPharnet.UserControls
{
    public partial class UCMasterData<T> : ControlViewBase
        where T : EntityObject, new()
    {
        #region Declarations
        Repository<T> lstMasterData;
        T currentObject;
        Enums.ActionForm _action = Enums.ActionForm.New;
        public delegate void RowSelectedEventHandler(object sender, RowSelectedArgs e);
        public event RowSelectedEventHandler RowSelected;
        bool closeForm = false;
        public bool CloseForm
        {
            get
            {
                return closeForm;
            }
            set
            {
                closeForm = value;
            }
        }
        #endregion

        #region Constructors
        public UCMasterData()
        {
            InitializeComponent();

        }
        #endregion

        #region Methods

        public void LoadLayoutGrid()
        {
            string fileXMLName = typeof(T).Name;
            string path = IOHelper.CombinePath(IOHelper.ExecutePath, string.Format(@"ListSchemaMasterData\{0}.xml", fileXMLName));
            grvMasterData.RestoreLayoutFromXml(path);

            // Set image for Delete button
            Image img = Image.FromFile(IOHelper.CombinePath(IOHelper.ExecutePath, @"Images\delete.png"));
            btnDelete = grvMasterData.Columns[1].ColumnEdit as RepositoryItemButtonEdit;
            btnDelete.Buttons[0].Kind = DevExpress.XtraEditors.Controls.ButtonPredefines.Glyph;
            btnDelete.Buttons[0].Image = img.GetThumbnailImage(18, 18, null, IntPtr.Zero);

            // Set image for Edit button
            img = Image.FromFile(IOHelper.CombinePath(IOHelper.ExecutePath, @"Images\edit.png"));
            btnEdit = grvMasterData.Columns[0].ColumnEdit as RepositoryItemButtonEdit;
            btnEdit.Buttons[0].Kind = DevExpress.XtraEditors.Controls.ButtonPredefines.Glyph;
            btnEdit.Buttons[0].Image = img.GetThumbnailImage(18, 18, null, IntPtr.Zero);
        }

        private void BindData()
        {
            List<T> lst;
            lstMasterData = new ListMasterData<T>().GetListData(out lst);
            grdMasterData.DataSource = lst;
        }

        private void BindDataToEditSection()
        {
            string name = string.Empty;
            string description = string.Empty;
            if (currentObject != null)
            {
                string objectType = typeof(T).ToString();
                switch (objectType)
                {
                    case Constant.ENT_MANUFACTURERGROUP:
                        {
                            ManufacturerGroup obj = currentObject as ManufacturerGroup;
                            name = obj.Name;
                            description = obj.Note;
                        } break;
                    case Constant.ENT_MASTERITEMGROUP:
                        {
                            MasterItemGroup obj = currentObject as MasterItemGroup;
                            name = obj.Name;
                            description = obj.Note;
                        } break;
                    case Constant.ENT_VENDORGROUP:
                        {
                            VendorGroup obj = currentObject as VendorGroup;
                            name = obj.Name;
                            description = obj.Note;
                        } break;
                    case Constant.ENT_CUSTOMERGROUP:
                        {
                            CustomerGroup obj = currentObject as CustomerGroup;
                            name = obj.Name;
                            description = obj.Note;
                        } break;
                    case Constant.ENT_EMPLOYEEGROUP:
                        {
                            EmployeeGroup obj = currentObject as EmployeeGroup;
                            name = obj.Name;
                            description = obj.Note;
                        } break;
                    case Constant.ENT_COUNTRY:
                        {
                            Country obj = currentObject as Country;
                            name = obj.Name;
                            description = obj.Note;
                        } break;
                    case Constant.ENT_PHARMACEUTICALFORM:
                        {
                            PharmaceuticalForm obj = currentObject as PharmaceuticalForm;
                            name = obj.Name;
                            description = obj.Note;
                        } break;
                    case Constant.ENT_UNITOFMEASURE:
                        {
                            UnitOfMeasure obj = currentObject as UnitOfMeasure;
                            name = obj.Name;
                            description = obj.Note;
                        } break;
                    case Constant.ENT_CATEGORY:
                        {
                            Category obj = currentObject as Category;
                            name = obj.Name;
                            description = obj.Note;
                        } break;
                    default:
                        break;
                }
            }
            txtName.EditValue = name;
            txtDescription.EditValue = description;
            _action = Enums.ActionForm.Edit;
            ChangeAction();
        }

        private void ChangeAction()
        {
            if (_action == Enums.ActionForm.Edit)
            {
                btnSave.Text = "Cập nhật";
                grdMasterData.Enabled = false;
            }
            else
            {
                btnSave.Text = "Nhập mới";
                grdMasterData.Enabled = true;
            }
        }

        private bool ValidateData()
        {
            if (txtName.Text.Length <= 0)
            {
                txtName.ErrorText = string.Format(Pharmacy.Ultilities.Resources.SR.Instance.GetString(Constant.KEY_EMPTYINFORMATION), "Tên");
                return false;
            }
            if (txtName.Text.Length > 250)
            {
                txtName.ErrorText = string.Format(Pharmacy.Ultilities.Resources.SR.Instance.GetString(Constant.KEY_INVALIDSTRINGLENGTH), "Tên", "250");
                return false;
            }
            return true;
        }

        public void CreateNew()
        {
            string objectType = typeof(T).ToString();
            switch (objectType)
            {
                case Constant.ENT_MANUFACTURERGROUP:
                    {
                        ManufacturerGroupBO manufacturerBO = new ManufacturerGroupBO();
                        ManufacturerGroup obj = manufacturerBO.CreateNewManufacturerGroup(txtName.Text.Trim(),
                            txtDescription.Text.Trim());
                    } break;
                case Constant.ENT_MASTERITEMGROUP:
                    {
                        MasterItemGroupBO masterItemGroupBO = new MasterItemGroupBO();
                        MasterItemGroup obj = masterItemGroupBO.CreateNewMasterItemGroup(txtName.Text.Trim(),
                            txtDescription.Text.Trim());
                    } break;
                case Constant.ENT_VENDORGROUP:
                    {
                        VendorGroupBO vendorGroupBO = new VendorGroupBO();
                        VendorGroup obj = vendorGroupBO.CreateNewVendorGroup(txtName.Text.Trim(),
                            txtDescription.Text.Trim());
                    } break;
                case Constant.ENT_CUSTOMERGROUP:
                    {
                        CustomerGroupBO customerGroupBO = new CustomerGroupBO();
                        CustomerGroup obj = customerGroupBO.CreateNewCustomerGroup(txtName.Text.Trim(),
                            txtDescription.Text.Trim());
                    } break;
                case Constant.ENT_EMPLOYEEGROUP:
                    {
                        EmployeeGroupBO employeeGroupBO = new EmployeeGroupBO();
                        EmployeeGroup obj = employeeGroupBO.CreateNewEmployeeGroup(txtName.Text.Trim(),
                            txtDescription.Text.Trim());
                    } break;
                case Constant.ENT_COUNTRY:
                    {
                        CountryBO countryBO = new CountryBO();
                        Country obj = countryBO.CreateNewCountry(txtName.Text.Trim(),
                            txtDescription.Text.Trim());
                    } break;
                case Constant.ENT_PHARMACEUTICALFORM:
                    {
                        PharmaceuticalFormBO pharmaceuticalFormBO = new PharmaceuticalFormBO();
                        PharmaceuticalForm obj = pharmaceuticalFormBO.CreateNewPharmaceuticalForm(txtName.Text.Trim(),
                            txtDescription.Text.Trim());
                    } break;
                case Constant.ENT_UNITOFMEASURE:
                    {
                        UnitOfMeasureBO unitOfMeasureBO = new UnitOfMeasureBO();
                        UnitOfMeasure obj = unitOfMeasureBO.CreateNewUnitOfMeasure(txtName.Text.Trim(),
                            txtDescription.Text.Trim());
                    } break;
                case Constant.ENT_CATEGORY:
                    {
                        CategoryBO categoryBO = new CategoryBO();
                        Category obj = categoryBO.CreateNewCategory(txtName.Text.Trim(),
                                                                    txtDescription.Text.Trim());
                    } break;
                default:
                    break;
            }
            BindData();
        }

        public string Edit()
        {
            if (currentObject != null)
            {
                string objectType = typeof(T).ToString();
                bool result = true;
                string messageError = string.Empty;
                switch (objectType)
                {
                    case Constant.ENT_MANUFACTURERGROUP:
                        {
                            using (ManufacturerGroupBO manufacturerBO = new ManufacturerGroupBO())
                            {
                                result = manufacturerBO.EditManufacturerGroup(
                                    (currentObject as ManufacturerGroup).ID,
                                    txtName.Text.Trim(),
                                    txtDescription.Text.Trim(),
                                    out messageError);
                                if (result == false)
                                {
                                    return messageError;
                                }
                            }
                        } break;
                    case Constant.ENT_MASTERITEMGROUP:
                        {
                            using (MasterItemGroupBO masterItemGroupBO = new MasterItemGroupBO())
                            {
                                result = masterItemGroupBO.EditMasterItemGroup(
                                    (currentObject as MasterItemGroup).ID,
                                    txtName.Text.Trim(),
                                    txtDescription.Text.Trim(),
                                    out messageError);
                                if (result == false)
                                {
                                    return messageError;
                                }
                            }
                        } break;
                    case Constant.ENT_VENDORGROUP:
                        {
                            using (VendorGroupBO vendorGroupBO = new VendorGroupBO())
                            {
                                result = vendorGroupBO.EditVendorGroup(
                                    (currentObject as VendorGroup).ID,
                                    txtName.Text.Trim(),
                                    txtDescription.Text.Trim(),
                                    out messageError);
                                if (result == false)
                                {
                                    return messageError;
                                }
                            }
                        } break;
                    case Constant.ENT_CUSTOMERGROUP:
                        {
                            using (CustomerGroupBO customerGroupBO = new CustomerGroupBO())
                            {
                                result = customerGroupBO.EditCustomerGroup(
                                    (currentObject as CustomerGroup).ID,
                                    txtName.Text.Trim(),
                                    txtDescription.Text.Trim(),
                                    out messageError);
                                if (result == false)
                                {
                                    return messageError;
                                }
                            }
                        } break;
                    case Constant.ENT_EMPLOYEEGROUP:
                        {
                            using (EmployeeGroupBO employeeGroupBO = new EmployeeGroupBO())
                            {
                                result = employeeGroupBO.EditEmployeeGroup(
                                    (currentObject as EmployeeGroup).ID,
                                    txtName.Text.Trim(),
                                    txtDescription.Text.Trim(),
                                    out messageError);
                                if (result == false)
                                {
                                    return messageError;
                                }
                            }
                        } break;
                    case Constant.ENT_COUNTRY:
                        {
                            using (CountryBO countryBO = new CountryBO())
                            {
                                result = countryBO.EditCountry(
                                    (currentObject as Country).ID,
                                    txtName.Text.Trim(),
                                    txtDescription.Text.Trim(),
                                    out messageError);
                                if (result == false)
                                {
                                    return messageError;
                                }
                            }
                        } break;
                    case Constant.ENT_PHARMACEUTICALFORM:
                        {
                            using (PharmaceuticalFormBO pharmaceuticalFormBO = new PharmaceuticalFormBO())
                            {
                                result = pharmaceuticalFormBO.EditPharmaceuticalForm(
                                    (currentObject as PharmaceuticalForm).ID,
                                    txtName.Text.Trim(),
                                    txtDescription.Text.Trim(),
                                    out messageError);
                                if (result == false)
                                {
                                    return messageError;
                                }
                            }
                        } break;
                    case Constant.ENT_UNITOFMEASURE:
                        {
                            using (UnitOfMeasureBO unitOfMeasureBO = new UnitOfMeasureBO())
                            {
                                result = unitOfMeasureBO.EditUnitOfMeasure(
                                    (currentObject as UnitOfMeasure).ID,
                                    txtName.Text.Trim(),
                                    txtDescription.Text.Trim(),
                                    out messageError);
                                if (result == false)
                                {
                                    return messageError;
                                }
                            }
                        } break;
                    case Constant.ENT_CATEGORY:
                        {
                            using (CategoryBO categoryBO = new CategoryBO())
                            {
                                result = categoryBO.EditCategory(
                                    (currentObject as Category).ID,
                                    txtName.Text.Trim(),
                                    txtDescription.Text.Trim(),
                                    out messageError);
                                if (result == false)
                                {
                                    return messageError;
                                }
                            }
                        } break;
                    default:
                        break;
                }
                BindData();
            }
            return string.Empty;
        }

        public string DeleteData()
        {
            if (currentObject != null)
            {
                string objectType = typeof(T).ToString();
                bool result = true;
                string messageError = string.Empty;
                switch (objectType)
                {
                    case Constant.ENT_MANUFACTURERGROUP:
                        {
                            using (ManufacturerGroupBO manufacturerBO = new ManufacturerGroupBO())
                            {
                                result = manufacturerBO.DeleteManufacturerGroup((currentObject as ManufacturerGroup).ID, out messageError);
                                if (result == false)
                                {
                                    return messageError;
                                }
                            }
                        } break;
                    case Constant.ENT_MASTERITEMGROUP:
                        {
                            using (MasterItemGroupBO masterItemGroupBO = new MasterItemGroupBO())
                            {
                                result = masterItemGroupBO.DeleteMasterItemGroup(
                                    (currentObject as MasterItemGroup).ID,
                                    out messageError);
                                if (result == false)
                                {
                                    return messageError;
                                }
                            }
                        } break;
                    case Constant.ENT_VENDORGROUP:
                        {
                            using (VendorGroupBO vendorGroupBO = new VendorGroupBO())
                            {
                                result = vendorGroupBO.DeleteVendorGroup(
                                    (currentObject as VendorGroup).ID,
                                    out messageError);
                                if (result == false)
                                {
                                    return messageError;
                                }
                            }
                        } break;
                    case Constant.ENT_CUSTOMERGROUP:
                        {
                            using (CustomerGroupBO customerGroupBO = new CustomerGroupBO())
                            {
                                result = customerGroupBO.DeleteCustomerGroup(
                                    (currentObject as CustomerGroup).ID,
                                    out messageError);
                                if (result == false)
                                {
                                    return messageError;
                                }
                            }
                        } break;
                    case Constant.ENT_EMPLOYEEGROUP:
                        {
                            using (EmployeeGroupBO employeeGroupBO = new EmployeeGroupBO())
                            {
                                result = employeeGroupBO.DeleteEmployeeGroup(
                                    (currentObject as EmployeeGroup).ID,
                                    out messageError);
                                if (result == false)
                                {
                                    return messageError;
                                }
                            }
                        } break;
                    case Constant.ENT_COUNTRY:
                        {
                            using (CountryBO countryBO = new CountryBO())
                            {
                                result = countryBO.DeleteCountry(
                                    (currentObject as Country).ID,
                                    out messageError);
                                if (result == false)
                                {
                                    return messageError;
                                }
                            }
                        } break;
                    case Constant.ENT_PHARMACEUTICALFORM:
                        {
                            using (PharmaceuticalFormBO pharmaceuticalFormBO = new PharmaceuticalFormBO())
                            {
                                result = pharmaceuticalFormBO.DeletePharmaceuticalForm(
                                    (currentObject as PharmaceuticalForm).ID,
                                    out messageError);
                                if (result == false)
                                {
                                    return messageError;
                                }
                            }
                        } break;
                    case Constant.ENT_UNITOFMEASURE:
                        {
                            using (UnitOfMeasureBO unitOfMeasureBO = new UnitOfMeasureBO())
                            {
                                result = unitOfMeasureBO.DeleteUnitOfMeasure(
                                    (currentObject as UnitOfMeasure).ID,
                                    out messageError);
                                if (result == false)
                                {
                                    return messageError;
                                }
                            }
                        } break;
                    case Constant.ENT_CATEGORY:
                        {
                            using (CategoryBO categoryBO = new CategoryBO())
                            {
                                result = categoryBO.DeleteCategory(
                                    (currentObject as Category).ID,
                                    out messageError);
                                if (result == false)
                                {
                                    return messageError;
                                }
                            }
                        } break;
                    default:
                        break;
                }
                BindData();
            }
            return string.Empty;
        }

        private void ClearData()
        {
            // Clear content
            txtDescription.Text = string.Empty;
            txtName.Text = string.Empty;
            // Clear error message
            txtDescription.ErrorText = string.Empty;
            txtName.ErrorText = string.Empty;
            currentObject = null;
            _action = Enums.ActionForm.New;
            ChangeAction();
        }

        private void InitializeForm()
        {
            string caption = Pharmacy.Ultilities.Resources.SR.Instance.GetString(typeof(T).FullName);
            // Set form's text
            if (ParentForm.GetType().Equals(typeof(DialogViewBase))
                || ParentForm.GetType().BaseType.Equals(typeof(DialogViewBase)))
            {
                DialogViewBase parent = ParentForm as DialogViewBase;
                if (parent != null)
                    parent.Text = caption;
            }
            // Set group control's text
            grpList.Text = caption;

            // Set image for Save button
            Image img = Image.FromFile(IOHelper.CombinePath(IOHelper.ExecutePath, @"Images\check2.png"));
            btnSave.Image = img.GetThumbnailImage(24, 24, null, IntPtr.Zero);

            // Set image for Cancel button
            img = Image.FromFile(IOHelper.CombinePath(IOHelper.ExecutePath, @"Images\delete2.png"));
            btnCancel.Image = img.GetThumbnailImage(24, 24, null, IntPtr.Zero);

            // Set image for Close button
            img = Image.FromFile(IOHelper.CombinePath(IOHelper.ExecutePath, @"Images\exit.png"));
            btnClose.Image = img.GetThumbnailImage(24, 24, null, IntPtr.Zero);

            // Set image for Export button
            img = Image.FromFile(IOHelper.CombinePath(IOHelper.ExecutePath, @"Images\export1.png"));
            btnExport.Image = img.GetThumbnailImage(24, 24, null, IntPtr.Zero);

        }

        private void OpenFile(string fileName)
        {
            if (MessageBox.Show("Do you want to open this file?", "Export File", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                try
                {
                    System.Diagnostics.Process process = new System.Diagnostics.Process();
                    process.StartInfo.FileName = fileName;
                    process.StartInfo.Verb = "Open";
                    process.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal;
                    process.Start();
                }
                catch (Exception ex)
                {
                    string message = "Cannot find an application on your system suitable for openning the file with exported data.";
                    ExceptionHandler.LogWriter.Write(ex.Message, ExceptionHandler.LOG_CAT_GENERAL);
                    MessageBox.Show(message);
                }
            }
        }

        private string ShowSaveFileDialog(string title, string filter)
        {
            SaveFileDialog dlg = new SaveFileDialog();
            string name = Application.ProductName;
            int n = name.LastIndexOf(".") + 1;
            if (n > 0) name = name.Substring(n, name.Length - n);
            dlg.Title = "Export To " + title;
            //dlg.FileName = name;
            dlg.FileName = this.FindForm().Text;
            dlg.Filter = filter;
            if (dlg.ShowDialog() == DialogResult.OK) return dlg.FileName;
            return "";
        }

        //IExportProvider provider
        private void ExportTo(GridView currentView, string fileName)
        {
            grdMasterData.FindForm().Refresh();
            currentView.OptionsPrint.PrintDetails = true;
            currentView.OptionsPrint.ExpandAllDetails = true;
            currentView.OptionsPrint.ExpandAllGroups = true;
            currentView.OptionsPrint.AutoWidth = false;
            XlsExportOptions option = new XlsExportOptions() { ShowGridLines = true };
            currentView.ExportToXls(fileName, option);
        }

        private void ExportToExcelWithoutDetail(GridView currentView, string fileName)
        {
            grdMasterData.FindForm().Refresh();
            if (currentView == null) return;
            GridViewExportLink gvlink;
            using (ExportXlsProvider provider = new ExportXlsProvider(fileName))
            {
                gvlink = (GridViewExportLink)currentView.CreateExportLink(provider);
                gvlink.ExpandAll = true;
                gvlink.ExportDetails = true;
                gvlink.ExportAll = true;
                gvlink.ExportTo(true);
            }
        }

        #endregion

        #region Event Handlers
        private void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                string messageError = string.Empty;
                if (ValidateData() == false)
                    return;
                ViewManager.CreateWaitDialog();
                ViewManager.SetWaitDialogCaption("Saving...");
                if (_action == Enums.ActionForm.New)
                    CreateNew();
                else if (_action == Enums.ActionForm.Edit)
                {
                    messageError = Edit();
                }
                if (messageError.Length == 0)
                    ClearData();
                else
                    MessageBox.Show(messageError);

            }
            catch (Exception ex)
            {
                ExceptionHandler.LogWriter.Write(ex.Message, ExceptionHandler.LOG_CAT_GENERAL);
                MessageBox.Show(ex.Message);
            }
            finally
            {
                ViewManager.CloseWaitDialog();
            }
        }

        private void UCMasterData_Load(object sender, EventArgs e)
        {
            try
            {
                InitializeForm();
                LoadLayoutGrid();
                BindData();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            try
            {
                if (ParentForm.GetType().Equals(typeof(DialogViewBase))
                    || ParentForm.GetType().BaseType.Equals(typeof(DialogViewBase)))
                {
                    DialogViewBase parent = ParentForm as DialogViewBase;
                    if (parent != null)
                        parent.Close();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Có lỗi xảy ra. Vui lòng liên hệ Người quản trị hệ thống để được hỗ trợ.");
                ExceptionHandler.LogWriter.Write(ex, ExceptionHandler.LOG_CAT_GENERAL);
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            try
            {
                ClearData();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Có lỗi xảy ra. Vui lòng liên hệ Người quản trị hệ thống để được hỗ trợ.");
                ExceptionHandler.LogWriter.Write(ex, ExceptionHandler.LOG_CAT_GENERAL);
            }
        }

        private void grvMasterData_CustomDrawRowIndicator(object sender, DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventArgs e)
        {
            try
            {
                if (e.Info.IsRowIndicator)
                {
                    if (e.RowHandle != GridControl.NewItemRowHandle && e.RowHandle != GridControl.AutoFilterRowHandle)
                    {
                        if (e.RowHandle < 0)
                        {
                            e.Info.DisplayText = "";
                        }
                        else
                        {
                            e.Info.DisplayText = (e.RowHandle + 1).ToString();
                        }
                    }
                    if (e.RowHandle == GridControl.AutoFilterRowHandle)
                    {
                        e.Info.ImageIndex = -1;
                        e.Info.DisplayText = "Filter";
                    }
                }
            }
            catch (Exception ex)
            {

                ExceptionHandler.LogWriter.Write(ex.Message, ExceptionHandler.LOG_CAT_GENERAL);
                MessageBox.Show(ex.Message);
            }
        }

        private void btnEdit_Click(object sender, EventArgs e)
        {
            try
            {
                if (grvMasterData.DataSource != null)
                {
                    int focusRow = grvMasterData.FocusedRowHandle;
                    currentObject = grvMasterData.GetRow(focusRow) as T;
                    BindDataToEditSection();
                }
            }
            catch (Exception ex)
            {

                ExceptionHandler.LogWriter.Write(ex.Message, ExceptionHandler.LOG_CAT_GENERAL);
                MessageBox.Show(ex.Message);
            }
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            try
            {
                if (grvMasterData.DataSource != null)
                {
                    ViewManager.CreateWaitDialog();
                    ViewManager.SetWaitDialogCaption("Saving...");
                    int focusRow = grvMasterData.FocusedRowHandle;
                    currentObject = grvMasterData.GetRow(focusRow) as T;
                    string messageError = DeleteData();
                    if (messageError.Length > 0)
                        MessageBox.Show(messageError);
                }
            }
            catch (UpdateException exc)
            {
                ExceptionHandler.LogWriter.Write(exc.Message, ExceptionHandler.LOG_CAT_GENERAL);
                MessageBox.Show(Pharmacy.Ultilities.Resources.SR.Instance.GetString(Constant.KEY_DELETEOBJECTINTRANSACTION));
            }
            catch (Exception ex)
            {

                ExceptionHandler.LogWriter.Write(ex.Message, ExceptionHandler.LOG_CAT_GENERAL);
                MessageBox.Show(ex.Message);
            }
            finally
            {
                ViewManager.CloseWaitDialog();
            }
        }

        private void btnExport_Click(object sender, EventArgs e)
        {
            try
            {
                string fileName = ShowSaveFileDialog("Microsoft Excel Document", "Microsoft Excel|*.xls");
                if (fileName != "")
                {
                    //new ExportXlsProvider(fileName)
                    //ExportTo(this.MainView as GridView, fileName);
                    //ExportTo(fileName);
                    string msg = Pharmacy.Ultilities.Resources.SR.Instance.GetString(Constant.EXPORTDATA_INCLUDEDETAIL);
                    if (MessageBox.Show(msg, Pharmacy.Ultilities.Resources.SR.Instance.GetString(Constant.EXPORTDATA_MESSAGETITLE), MessageBoxButtons.YesNo) == DialogResult.Yes)
                    {
                        ExportTo(grvMasterData, fileName);
                    }
                    else
                    {
                        ExportToExcelWithoutDetail(grvMasterData, fileName);
                    }
                    OpenFile(fileName);
                }
            }
            catch (Exception ex)
            {

                ExceptionHandler.LogWriter.Write(ex.Message, ExceptionHandler.LOG_CAT_GENERAL);
                MessageBox.Show(ex.Message);
            }
        }

        private void grdMasterData_DoubleClick(object sender, EventArgs e)
        {
            EntityObject item = grvMasterData.GetRow(grvMasterData.FocusedRowHandle) as EntityObject;
            if (item == null)
            {
                return;
            }
            GridHitInfo ghi = grvMasterData.CalcHitInfo((e as MouseEventArgs).Location);
            if (!ghi.InRow)
            {
                return;
            }

            RowSelectedArgs args = new RowSelectedArgs();
            args.CurrentSelectedRowID = Convert.ToInt32(item.EntityKey.EntityKeyValues[0].Value);
            if (RowSelected != null)
            {
                RowSelected(sender, args);
                btnClose.PerformClick();
            }
        }
        #endregion
        
    }
}
